<template>
  <el-dialog :title="title" :visible.sync="dialogShow" @close="closeDialog">
    <!-- //!绘制表单 -->
    <el-form
      ref="form"
      :model="formData"
      :rules="formRules"
      label-width="160px"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width: 440px" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width: 440px" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="formData.manager"
          placeholder="请选择"
          style="width: 440px"
          @focus="getEmployeeData"
        >
          <!-- label:字段指定是显示的文字字段  value:指的是将那个字段的数据给v-model绑定的变量 -->
          <el-option
            v-for="(item, index) in managerList"
            :key="index"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="formData.introduce"
          style="width: 440px"
          rows="3"
          type="textarea"
        />
      </el-form-item>
      <el-row type="flex" justify="center">
        <el-button size="small" type="primary" @click="btnOk">确定</el-button>
        <el-button size="small" @click="dialogShow = false">取消</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script>
import { getEmployeeSimpleApi } from '@/api/employees'
import {
  getDepartmentListApi,
  addDepartmentApi,
  getDepartmentInfoApi,
  editDepartmentApi
} from '@/api/department'

export default {
  name: 'AddDept',
  data() {
    // 部门名称的校验
    const checkNameRepeat = async (valid, value, cb) => {
      console.log(valid)
      // 1.找到所有部门名称
      const { depts } = await getDepartmentListApi()
      // 2.找到当前部门的兄弟部门(如果是编辑状态下，还要排除自己)
      console.log('找到pid是' + this.formData.pid + '说明就是兄弟')
      let arr = depts.filter((item) => item.pid === this.formData.pid)
      console.log(arr)
      if (this.formData.id) {
        arr = arr.filter((item) => item.id !== this.formData.id)
      }
      // 3.名称查重
      const isRepeat = arr.some((item) => item.name === value)
      isRepeat ? cb(new Error('名称重复')) : cb()
    }
    // 部门编码的校验
    const checkCodeRepeat = async (valid, value, cb) => {
      console.log(valid)
      // 1.找到所有部门名称((如果是编辑状态下，还要排除自己))
      let { depts } = await getDepartmentListApi()
      if (this.formData.id) {
        depts = depts.filter((item) => item.id !== this.formData.id)
      }
      // 2.名称查重
      const isRepeat = depts.some((item) => item.code === value)
      isRepeat ? cb(new Error('编码重复')) : cb()
    }
    return {
      // 是否显示弹框
      dialogShow: false,
      // 表单数据变量
      formData: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      },
      // 表单验证规则
      formRules: {
        code: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: checkCodeRepeat, trigger: 'blur' }
        ],
        introduce: [{ required: true, message: '请输入', trigger: 'blur' }],
        manager: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: checkNameRepeat, trigger: 'blur' }
        ]
      },
      // 负责人数据
      managerList: []
    }
  },
  computed: {
    title() {
      return this.formData.id ? '修改' : '新增'
    }
  },
  methods: {
    // 获取负责人数据
    async getEmployeeData() {
      this.managerList = await getEmployeeSimpleApi()
    },
    // 提交事件逻辑
    async btnOk() {
      // 1.表单数据校验
      console.log(this.$refs.form) // !获取到el-form组件实例
      // this.$refs.form.validate((valid) => {
      //   console.log(valid) // valid布尔值，表示校验是否通过
      // })
      try {
        await this.$refs.form.validate()
      } catch (e) {
        return console.log(e)
      }
      // 2.发送请求

      // 3.提示成功
      if (this.formData.id) {
        await editDepartmentApi(this.formData)
        this.$message.success('编辑成功')
      } else {
        await addDepartmentApi(this.formData)
        this.$message.success('添加成功')
      }

      // 4.更新列表
      this.$emit('updataList')
      // 5.关闭弹窗，重置表单
      this.dialogShow = false
    },
    // 关闭弹框
    closeDialog() {
      console.log('关闭弹框')
      // 重置表单的逻辑写在这里(点击叉号，点击黑色阴影区域，dialogShow为false三者之一)
      this.formData = {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      }
      // !移除校验
      console.log(this.$refs.form)
      this.$refs.form.clearValidate()
    },
    // 获取回显的数据
    async getFormDataInfo(ID) {
      // 请求数据
      const res = await getDepartmentInfoApi(ID)
      console.log(res)
      // 回显给表单
      this.formData = res
      // 弹框打开
      this.dialogShow = true
    }
  }
}
</script>

<style></style>
